package com.bcx.wind.workflow.access;

import com.bcx.wind.workflow.db.util.handler.ResultSetHandler;
import com.bcx.wind.workflow.support.JsonHelper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 工作流持久层返回结果类型处理器
 *
 * @param <T>  类型
 * @author zhanglei
 */
public class WindResultSetHandler<T> implements ResultSetHandler {

    private final Class<T> clazz;

    public WindResultSetHandler(Class<T> clazz){
        this.clazz = clazz;
    }

    @Override
    public Object handle(ResultSet resultSet) throws SQLException {
        ResultSetMetaData metaData = resultSet.getMetaData();
        //列数量
        int columns = metaData.getColumnCount();
        List<Map<String,Object>> datas = new LinkedList<>();
        while(resultSet.next()){
            Map<String,Object> data = new HashMap<>(16);
            for(int i=1; i<=columns ; i++){
                String columnName = metaData.getColumnName(i);
                Object object = resultSet.getObject(columnName);
                columnName = JsonHelper.toHump(columnName);
                data.put(columnName,object);
            }
            datas.add(data);
        }

        if(clazz.isAssignableFrom(Map.class)){
            return datas;
        }
        return JsonHelper.coverObject(datas,List.class,clazz);
    }
}
